<template>
  <div class="game-detail-container">
    <!-- 游戏主要信息区域 -->
    <div class="game-main-info">
      <!-- 游戏封面图 -->
      <div class="game-cover" v-if="gameDetail">
        <!-- 图片占位符 -->
        <div class="image-placeholder" v-if="coverType == 'img' && !imageLoaded"></div>

        <!-- 主图片，添加淡入过渡效果 -->
        <img v-if="coverType == 'img' && coverUrl" :src="coverUrl" :alt="gameDetail.title" class="cover-image"
          :class="{ 'image-loaded': imageLoaded }" @load="imageLoaded = true" />

        <!-- 视频 -->
        <video v-else-if="coverSrc" :src="coverSrc" class="cover-image" autoplay muted loop
          :class="{ 'image-loaded': imageLoaded }">
        </video>

        <!-- 缩略图列表 -->
        <div class="thumbnail-list">
          <div v-for="(thumbnail, index) in thumbnails" :key="index" class="thumbnail-item"
            :class="{ active: selectIndex === index }" @click="switchCover(thumbnail, index)">
            <!-- 缩略图占位符 -->
            <div class="thumbnail-placeholder" v-if="!thumbnail.imageUrl || !imageLoaded"></div>
            <img v-if="thumbnail.imageUrl" :src="thumbnail.imageUrl" :alt="`${gameDetail.title} 缩略图${index + 1}`"
              class="thumbnail-image" :class="{ 'image-loaded': imageLoaded }" />
          </div>
        </div>
      </div>

      <!-- 游戏详细信息 -->
      <div class="game-info">
        <!-- 游戏标题 -->
        <h1 class="game-title">{{ gameDetail.title }}</h1>

        <!-- 游戏分类标签 -->
        <div class="game-categories">
          <el-tag v-for="category in gameDetail.tags" :key="category" class="category-tag">
            {{ category.name }}
          </el-tag>
        </div>

        <!-- 游戏简介 -->
        <div class="game-description">
          {{ gameDetail.intro }}
        </div>

        <!-- 秒玩按钮 -->
        <div class="play-button-container">
          <!-- 游戏详细信息 -->
          <div class="game-detail-info">
            <!-- 账号分享信息 -->
            <div>
              <div class="account-info" v-if="gameDetail.accountSharer">
                <el-popover placement="top" width="170" :show-arrow="false" popper-class="custom-popover">
                  <template #reference>
                    <img src="@/assets/images/header/ihover.png" alt="时间图标" class="time-icon-image" />
                  </template>
                  <p style="margin: 0">该游戏账号由玩家分享</p>
                </el-popover>
                <span class="account-label">账号分享：</span>
                <span class="account-value">{{gameDetail.accountSharer}}</span>
              </div>
              <div class="account-info" v-if="gameDetail.gameSharer">
                <el-popover placement="top" width="170" :show-arrow="false" popper-class="custom-popover">
                  <template #reference>
                    <img src="@/assets/images/header/ihover.png" alt="时间图标" class="time-icon-image" />
                  </template>
                  <p style="margin: 0">该游戏版本由玩家分享</p>
                </el-popover>
                <span class="account-label">游戏分享：</span>
                <span class="account-value">{{ gameDetail.gameSharer }}</span>
              </div>
            </div>
            <!-- 游戏时长信息 -->
            <div class="game-time-info">
              <span class="time-icon">
                <el-icon>
                  <img src="@/assets/images/header/dou.png" alt="时间图标" class="time-icon-image" />
                </el-icon>
              </span>
              <span class="time-value">{{ gameDetail.coin }}小时</span>
            </div>
          </div>

          <el-button type="primary" class="play-button" v-if="MyStart == 0" :loading="isPlaying"
            @click="gameDetailHandlePlayGame">
            秒玩
          </el-button>
          <el-button type="primary" class="play-button" v-if="MyStart == 1" :loading="isPlaying"
            @click="gameDetailHandlePlayGame">
            继续游戏
          </el-button>
          <el-button type="primary" class="play-button" v-if="MyStart == -1" :loading="isPlaying"
            @click="handleRecharge">
            资源不足，请去充值
          </el-button>
          <el-button type="primary" class="play-button" v-if="MyStart == 3" :loading="isPlaying"
            @click="showCloseClient = true">
            游戏启动中...
          </el-button>
        </div>
      </div>
    </div>

    <!-- 相关游戏推荐 -->
    <div class="related-games-section">
      <h2 class="section-title">大家都在玩</h2>
      <div class="related-games-grid">
        <el-card v-for="(relatedGame, index) in relatedGames" :key="index" class="related-game-card" shadow="never"
          @click="navigateToGameDetail(relatedGame.id)">
          <div class="related-game-content">
            <div class="related-game-image">
              <img :src="relatedGame.coverUrl" :alt="relatedGame.title" />
            </div>
            <div class="related-game-info">
              <h3 class="related-game-title">{{ relatedGame.title }}</h3>
              <p class="related-game-desc">{{ relatedGame.slogan }}</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 实名认证弹窗 -->
    <RealName v-model="showRealName" @close="showRealName = false" />

    <!-- 充值中心弹窗 -->
    <RechargeCenter v-model="rechargeVisible" @close="rechargeVisible = false" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";
import { gameApi } from "@/api/game.js";
import { useLoginCheck, handlePlayGame } from "@/utils/auth.js";
import RealName from "@/components/RealName.vue";
import RechargeCenter from "@/components/RechargeCenter.vue";

// 用户store
const userStore = useUserStore();
// 路由实例
const route = useRoute();
const router = useRouter();

// 游戏封面图
const selectIndex = ref(0);
const coverType = ref("img");
const coverUrl = ref("");
const coverSrc = ref("");

// 图片加载状态
const imageLoaded = ref(false);
const isBackgroundReady = ref(false);

// 游戏详情数据
const gameDetail = ref({});

// 缩略图列表
const thumbnails = ref([]);

// 相关游戏数据
const relatedGames = ref([]);

// 游戏加载状态
const isPlaying = ref(false);

// 引入登录检查模块
const { checkAndPerform } = useLoginCheck();

// 实名认证弹窗状态
const showRealName = ref(false);

// 关闭客户端弹窗状态
const closeClientDialogVisible = ref(false);
const showCloseClient = ref(false);
const useAccountWay = ref(1); //使用游戏账号方式:0=不使用账号；1：使用官方共享账号；默认为0
// 关闭客户端弹窗的status状态 (新增)
const closeClientStatus = ref(1); // 设置为1，表示"切换游戏"

const rechargeVisible = ref(false);

// 是否
const MyStart = ref(0);

// 预加载图片函数
const preloadImage = (url) => {
  return new Promise((resolve, reject) => {
    if (!url) {
      reject(new Error('URL为空'));
      return;
    }
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = reject;
    img.src = url;
  });
};

// 批量预加载图片
const preloadImages = async (urls) => {
  if (!urls || !Array.isArray(urls)) return;
  const promises = urls.map(url => preloadImage(url).catch(err => {
    console.error(`图片预加载失败: ${url}`, err);
    return null;
  }));
  await Promise.allSettled(promises);
};

// 组件挂载时执行
onMounted(() => {
  // 获取路由参数中的游戏ID
  const gameId = route.params.gameId || "";
  if (gameId) {
    fetchGameDetail(gameId);
    etRecommendedGames(gameId);
  }
});
// 获取游戏详情
const fetchGameDetail = async (id) => {
  var panams = {
    id: id,
  };
  try {
    const res = await gameApi.getGameDetail(panams);
    gameDetail.value = res.info || {};

    // 收集需要预加载的图片URL
    const imageUrls = [];

    if (res.info.videoUrl) {
      thumbnails.value.push({
        gameId: "video",
        imageUrl: res.info.coverUrl || "",
      });
      coverSrc.value = res.info.videoUrl || "";
      coverType.value = "video";
      if (res.info.coverUrl) {
        imageUrls.push(res.info.coverUrl);
      }
    } else if (res.info.images && res.info.images.length > 0) {
      coverUrl.value = res.info.images[0].imageUrl || "";
      coverType.value = "img";
      if (res.info.images[0].imageUrl) {
        imageUrls.push(res.info.images[0].imageUrl);
      }
    }

    //合并数组
    thumbnails.value = [...thumbnails.value, ...res.info.images];

    // 收集所有缩略图URL进行预加载
    res.info.images.forEach(img => {
      if (img.imageUrl) {
        imageUrls.push(img.imageUrl);
      }
    });

    // 预加载所有图片
    await preloadImages(imageUrls);

    // 设置加载状态
    imageLoaded.value = true;

    if (res.info.qualificationStatus == -1) {
      MyStart.value = -1; //资源不足
    } else {
      if (res.info.session && res.info.session.status == "online") {
        MyStart.value = 1; //游戏已启动
      } else {
        MyStart.value = 0; //游戏启动中
      }
    }

    // 设置背景图
    await setBackgroundImage();
  } catch (err) {
    console.error("获取游戏详情失败:", err);
    // 即使出错也要确保UI有反馈
    imageLoaded.value = true;
  }
};
// 获取相关游戏
const etRecommendedGames = (id) => {
  var panams = {
    id: id,
  };
  gameApi.etRecommendedGames(panams).then((res) => {
    relatedGames.value = res.games || [];
  }).catch((err) => {
    console.error("获取相关游戏失败:", err);
  });
};

// 使用全局handlePlayGame方法
const handlePlayGameCallback = (status, data) => {
  switch (status) {
    case "cancel": //取消
      isPlaying.value = false;
      break;
    case "confirm": //确认
      isPlaying.value = false;
      // 传入目标类型:1=云游戏;2=云电脑
      handlePlayGame(gameDetail.value.id, "1", handlePlayGameCallback, 0);
      break;
  }
};

// 调用全局秒玩游戏处理函数
const gameDetailHandlePlayGame = () => {
  isPlaying.value = true;
  // 传入目标类型:1=云游戏;2=云电脑
  handlePlayGame(gameDetail.value.id, "1", handlePlayGameCallback, 1);
};

// 打开充值中心弹窗
const handleRecharge = () => {
  // 检查登录并执行操作
  checkAndPerform(() => {
    rechargeVisible.value = true;
  });
};
// 跳转到其他游戏详情页
const navigateToGameDetail = (id) => {
  router.push({
    path: `/cloudGaming/detail/${id}`,
  });
};

// 切换封面图
const switchCover = async (thumbnail, index) => {
  // 先重置加载状态
  imageLoaded.value = false;
  isBackgroundReady.value = false;

  if (thumbnail.gameId == "video") {
    coverSrc.value = gameDetail.value.videoUrl || "";
    coverUrl.value = thumbnail.imageUrl || "";
    selectIndex.value = index;
    coverType.value = "video";
  } else {
    coverUrl.value = thumbnail.imageUrl || "";
    selectIndex.value = index;
    coverType.value = "img";
  }

  // 预加载当前图片
  if (coverUrl.value) {
    try {
      await preloadImage(coverUrl.value);
      imageLoaded.value = true;
    } catch (err) {
      console.error("切换封面图预加载失败:", err);
      imageLoaded.value = true; // 即使失败也要显示
    }
  }

  // 更新背景图
  await setBackgroundImage();
};

// 设置背景图
const setBackgroundImage = async () => {
  if (!coverUrl.value) return;

  try {
    // 先预加载背景图
    await preloadImage(coverUrl.value);

    // 修改.el-main的背景图
    const mainElement = document.querySelector(".el-main");
    if (mainElement) {
      // 添加过渡效果
      mainElement.style.transition = "background-image 0.5s ease-in-out";

      mainElement.style.backgroundImage = `url(${coverUrl.value})`;
      mainElement.style.backgroundSize = "cover";
      mainElement.style.backgroundPosition = "center";
      mainElement.style.backgroundRepeat = "no-repeat";
      mainElement.style.backgroundAttachment = "fixed";
      // 添加背景模糊和变暗效果
      mainElement.style.position = "relative";
      mainElement.style.overflow = "hidden";

      // 创建或更新背景遮罩层
      let overlay = mainElement.querySelector(".bg-overlay");
      if (!overlay) {
        overlay = document.createElement("div");
        overlay.className = "bg-overlay";
        overlay.style.position = "absolute";
        overlay.style.top = "0";
        overlay.style.left = "0";
        overlay.style.width = "100%";
        overlay.style.height = "100%";
        overlay.style.background = "rgba(0, 0, 0, 0.8)";
        overlay.style.zIndex = "0";
        overlay.style.backdropFilter = "blur(5px)";
        mainElement.appendChild(overlay);
      }

      // 确保内容在遮罩层之上
      const contentElement = mainElement.querySelector(
        ".game-detail-container"
      );
      if (contentElement) {
        contentElement.style.position = "relative";
        contentElement.style.zIndex = "1";
      }

      // 标记背景图准备完成
      setTimeout(() => {
        isBackgroundReady.value = true;
      }, 100);
    }
  } catch (err) {
    console.error("设置背景图失败:", err);
    // 错误处理
    isBackgroundReady.value = true;
  }
};

// 组件卸载时恢复.el-main的背景样式
onUnmounted(() => {
  const mainElement = document.querySelector(".el-main");
  if (mainElement) {
    // 恢复背景样式为#121517
    mainElement.style.background = "#121517";
    // 移除所有背景相关样式
    mainElement.style.backgroundImage = "";
    mainElement.style.backgroundSize = "";
    mainElement.style.backgroundPosition = "";
    mainElement.style.backgroundRepeat = "";
    mainElement.style.backgroundAttachment = "";
    mainElement.style.position = "";
    mainElement.style.overflow = "";

    // 移除背景遮罩层
    const overlay = mainElement.querySelector(".bg-overlay");
    if (overlay && overlay.parentNode === mainElement) {
      mainElement.removeChild(overlay);
    }

    // 移除内容的z-index样式
    const contentElement = mainElement.querySelector(".game-detail-container");
    if (contentElement) {
      contentElement.style.position = "";
      contentElement.style.zIndex = "";
    }
  }
});
</script>

<style lang="scss" scoped>
.game-detail-container {
  .game-main-info {
    display: flex;
    gap: 20px;
    margin-bottom: 50px;

    .game-cover {
      flex: 0 0 auto;
      width: 564px;
      height: 390px;
      border-radius: 4px;
      overflow: hidden;

      .cover-image {
        width: 564px;
        height: 316px;
        display: block;
        object-fit: cover;
        transition: opacity 0.5s ease-in-out;
        opacity: 0;
        background: transparent !important;

        &.image-loaded {
          opacity: 1;
        }
      }

      .image-placeholder {
        width: 564px;
        height: 316px;
        background: #2a2a2a;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;

        // 添加加载动画
        animation: pulse 1.5s ease-in-out infinite;
      }

      @keyframes pulse {

        0%,
        100% {
          opacity: 0.6;
        }

        50% {
          opacity: 0.8;
        }
      }

      // 缩略图列表样式
      .thumbnail-list {
        flex: 0 0 auto;
        width: 564px;
        display: flex;
        gap: 10px;
        margin-top: 15px;

        .thumbnail-item {
          // flex: 1;
          width: 100px;
          height: 57px;
          border-radius: 4px;
          overflow: hidden;
          cursor: pointer;
          border: 1px solid transparent;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            border-color: #ffaa00;
          }

          &.active {
            border: 1px solid #fff;
          }

          .thumbnail-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: all 0.3s ease;
            opacity: 0;

            &.image-loaded {
              opacity: 1;
            }

            &:hover {
              transform: scale(1.05);
            }
          }

          .thumbnail-placeholder {
            width: 100%;
            height: 100%;
            background: #2a2a2a;
            border-radius: 4px;
          }
        }
      }
    }

    .game-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 20px;
      padding: 20px;
      background: #121517;
      border-radius: 4px;

      .game-title {
        font-size: 24px;
        font-weight: 700;
        color: #ffffff;
        margin: 0;
        line-height: 1.2;
      }

      .game-categories {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;

        .category-tag {
          border: none;
          background-color: #272727;
          color: #e2e2e2;
          font-size: 12px;
        }
      }

      .game-description {
        font-size: 12px;
        color: #949495;
        line-height: 1.8;
        margin: 0;
      }

      .game-detail-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-top: 1px solid rgba(255, 255, 255, 0.1);

        .account-info {
          display: flex;
          align-items: center;
          gap: 5px;
          color: #fff;

          .account-label {
            font-size: 14px;
          }

          .account-value {
            font-size: 14px;
            font-weight: 500;
          }
        }

        .game-time-info {
          display: flex;
          align-items: center;
          gap: 8px;

          .time-icon {
            color: #ffaa00;

            .time-icon-image {
              width: 16px;
              height: 16px;
              display: inline-block;
            }
          }

          .time-value {
            font-size: 14px;
            color: #ffffff;
          }
        }
      }

      .play-button-container {
        margin-top: auto;

        .play-button {
          width: 100%;
          height: 48px;
          border: none;
          background: linear-gradient(90deg, #fee300 0%, #f79f17 100%);
          color: #121212;
          font-size: 14px;
          font-weight: 600;
          transition: all 0.3s ease;

          &:hover {
            background-color: #ffbb33;
            border-color: #ffbb33;
            transform: translateY(-1px);
          }

          &:active {
            transform: translateY(0);
          }
        }
      }
    }
  }

  .related-games-section {
    .section-title {
      font-size: 20px;
      font-weight: 600;
      color: #ffffff;
      margin: 0 0 20px 0;
    }

    .related-games-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;

      .related-game-card {
        background-color: #1a1c1e;
        border-radius: 4px;
        overflow: hidden;
        border: none;
        transition: all 0.3s ease;
        cursor: pointer;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
          background-color: #232526;
        }

        .related-game-content {
          width: 100%;

          .related-game-image {
            width: 100%;
            aspect-ratio: 16 / 9;
            overflow: hidden;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
              transition: transform 0.3s ease;

              &:hover {
                transform: scale(1.05);
              }
            }
          }

          .related-game-info {
            padding: 16px 0;

            .related-game-title {
              font-size: 16px;
              font-weight: 600;
              color: #ffffff;
              margin: 0 0 8px 0;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .related-game-desc {
              font-size: 14px;
              color: #949495;
              margin: 0;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }
    }
  }
}
</style>
